<?php

namespace app\controller\install;

use core\traits\Response as TraitsResponse;
use Exception;
use hulang\tool\FileHelper;
use hulang\tool\StrHelper;
use Illuminate\Support\Facades\DB as FacadesDB;
use PDO;
use PDOException;
use support\Db;
use Throwable;
use Utopia\Domains\Domain;

class Index
{
    use TraitsResponse;
    public function index()
    {



        if (!file_exists(base_path() . '/install.lock')) {
            return $this->error('', 404);
        }
        if (request()->isPost()) {
            $data     = request()->post();

            $type = request()->get('type');
            switch ($type) {
                case 'setdatabase':

                    $host     = $data['dbhost'];
                    $port     = $data['dbport'];
                    $username = $data['dbusername'];
                    $password = $data['dbpassword'];
                    $database = $data['dbdatabase'];
                    $prefix   = $data['dbprefix'];
                    $safe_key = StrHelper::Random(16);
                    $domain         = new Domain(request()->host());
                    $registerable   = $domain->getRegisterable();
                    $session_domain = $registerable == '' ? '' : '.' . $registerable;

                    try {
                        $dsn = "mysql:host=$host;port=$port;charset=utf8mb4";
                        $pdo = new PDO($dsn, $username, $password);
                        $pdo->query('CREATE DATABASE ' . $database . ' CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;');

                        //设置配置文件

                        $databasestr =   file_get_contents(base_path() . '/.env');
                        $databasestr = str_replace([
                            '{{host}}',
                            '{{port}}',
                            '{{database}}',
                            '{{username}}',
                            '{{password}}',
                            '{{prefix}}',
                            '{{session_domain}}',
                            '{{safe_key}}',
                        ], [
                            $host,
                            $port,
                            $database,
                            $username,
                            $password,
                            $prefix,
                            $session_domain,
                            $safe_key
                        ], $databasestr);
                        file_put_contents(base_path() . '/.env', $databasestr);
                    } catch (PDOException $e) {
                        return $this->error($e->getMessage());
                    } catch (Throwable $ex) {
                        return $this->error($ex->getMessage());
                    }

                    return $this->success();
                    break;

                case 'installsql':
                    try {

                        $sqlstr = file_get_contents(base_path() . '/template/install/install.sql');
                        $sqlstr = str_replace('{{prefix}}', $data['dbprefix'], $sqlstr);
                        Db::connection(config('database.default'))->unprepared($sqlstr);
                    } catch (Exception $ex) {
                        return $this->error($ex->getMessage());
                    } catch (Throwable $ex) {
                        return $this->error($ex->getMessage());
                    }


                    return $this->success();
                    break;


                case 'createadmin':
                    Db::beginTransaction();
                    try {
                        $uid = Db::table('frame_user')
                            ->insertGetId([
                                'username' => $data['username'],
                                'phone'    => $data['phone'],
                                'email'    => $data['email'],
                                'pwd'      => password_hash($data['password'], PASSWORD_DEFAULT)
                            ]);

                        Db::table('frame_admin')
                            ->insert([
                                'uid' => $uid,
                                'issystem' => 1

                            ]);

                        Db::table('frame_site')
                            ->insert([
                                'ident' => 'main',
                                'domain' => request()->host(),
                                'title' => '默认网站',
                                'status' => 1

                            ]);
                        Db::commit();
                    } catch (Throwable $ex) {
                        Db::rollBack();
                        return $this->error($ex->getMessage());
                    }

                    //安装成功 
                    FileHelper::delFile(base_path() . '/install.lock');
                    return $this->success();
                    break;
            }
        } else {

            return view('/template/install/index');
        }
    }
}
